<template>
    <ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto">
        <div style="padding: 10px">
            <el-card class="box-card" shadow="hover">
                <!--新增区域-->
                <div style="margin: 10px 0" v-if="user.role===1">
                    <el-button class="el_botton" icon="el-icon-plus" type="primary" @click="add">新增</el-button>
                    <el-popconfirm
                            v-if="user.role === 1"
                            title="确定删除吗？"
                            @confirm="deleteBatch"
                    >
                        <template #reference>
                            <el-button icon="el-icon-delete" type="danger">批量删除</el-button>
                        </template>
                    </el-popconfirm>
                </div>

                <!--搜索、查询区域-->
                <div style="margin: 10px 0">
                    <el-input v-model="pageInfo.query" placeholder="按名称查询" style="width: 20%" clearable></el-input>
                    <el-button class="el_botton" icon="el-icon-search" type="primary" style="margin-left: 5px" @click="load">查询</el-button>
                    <el-button v-if="user.role===2" type="warning" @click="orderQuery">预约查询</el-button>
                </div>


                <!--数据表格-->
                <el-table :data="tableData" stripe border style="width: 100%"
                          @selection-change="handleSelectionChange">
                    <el-table-column
                            type="selection"
                            width="100">
                    </el-table-column>
                    <el-table-column label="图片">
                        <template #default="scope">
                            <el-image
                                    style="width: 160px;height: 120px"
                                    :src="scope.row.image"
                                    :preview-src-list="[scope.row.image]"
                            ></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="名称"></el-table-column>
                    <el-table-column prop="count" label="余量"></el-table-column>
                    <el-table-column prop="place" label="接种地点"></el-table-column>
                    <el-table-column label="描述">
                        <template #default="scope">
                            <el-button size="mini" type="success" plain @click="detalts1(scope.row)">详情介绍
                            </el-button>
                        </template>
                    </el-table-column>
<!--                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="mini" v-if="user.role===2" type="primary" plain
                                       @click="changeVis3(scope.row)">预约
                            </el-button>
                            <el-button size="mini" v-if="user.role===1" type="warning" @click="handleEdit(scope.row)">
                                编辑
                            </el-button>
                            <el-popconfirm v-if="user.role===1" title="确认删除吗？" @confirm="handleDelete(scope.row.id)">
                                <template #reference>
                                    <el-button size="mini" type="danger">删除
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>-->
                    <el-table-column show-overflow-tooltip label="操作" width="180px">
                        <template #default="scope">
                            <el-button type="text" v-if="user.role===2" @click="changeVis3(scope.row)">预约</el-button>
                            <el-button type="text" v-if="user.role===1" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-popconfirm v-if="user.role===1" title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
                                <template #reference>
                                    <el-button type="text">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>

                <!--分页-->
                <div style="margin: 10px 0">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="pageInfo.pageNum"
                            :page-sizes="[5, 10, 20]"
                            :page-size="pageInfo.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                    </el-pagination>
                </div>
            </el-card>

            <!--添加按钮的弹出框-->
            <el-dialog title="提示" v-model="dialogVisible" width="30%">
                <el-form :model="form" label-width="120px">
                    <el-form-item label="名称">
                        <el-input v-model="form.name" style="width: 80%"></el-input>
                    </el-form-item>
                    <el-form-item label="图片">
                        <el-upload ref="upload" action="http://localhost:9090/files/upload"
                                   :on-success="filesUpload">
                            <el-button type="primary">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="余量">
                        <el-input v-model="form.count" style="width: 80%"></el-input>
                    </el-form-item>
                    <el-form-item label="接种地点">
                        <el-input
                                type="textarea"
                                :rows="2"
                                placeholder="请输入疫苗接种地点"
                                v-model="form.place">
                        </el-input>
                    </el-form-item>
                    <div id="div1"></div>
                </el-form>
                <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
                </template>
            </el-dialog>


            <el-dialog title="公告" v-model="vis" width="50%">
                <el-card>
                    <div v-html="detalt.place" style="min-height: 100px"></div>
                </el-card>
            </el-dialog>

            <el-dialog title="详情介绍" v-model="vis2" width="50%">
                <el-card>
                    <div v-html="detalt.details" style="min-height: 100px"></div>
                </el-card>
            </el-dialog>

            <!--预约弹出框-->
            <el-dialog title="预约信息表" v-model="vis3" width="30%" :before-close="handleDialogClose">
                <el-form :model="form" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                         class="demo-ruleForm" >
                    <el-form-item label="疫苗名称:">
                        <el-input v-model="form.vaccineName" style="width: 80%" readonly="true"></el-input>
                    </el-form-item>
                    <el-form-item label="接种人:" prop="name">
                        <el-input v-model="form.name" style="width: 80%" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话:" prop="phone">
                        <el-input v-model="form.phone" style="width: 80%" placeholder="请输入联系方式"></el-input>
                    </el-form-item>
                    <el-form-item label="家庭住址:" prop="address">
                        <el-input v-model="form.address" style="width: 80%" placeholder="请输入家庭住址"></el-input>
                    </el-form-item>
                    <el-form-item label="风险地区:" prop="risk">
                        <el-radio v-model="form.risk" label="1">是</el-radio>
                        <el-radio v-model="form.risk" label="0">否</el-radio>
                    </el-form-item>
                    <el-form-item label="接种地点:" prop="vaccinePlace">
                        <el-select v-model="form.vaccinePlace" placeholder="请选择">
                            <el-option
                                    v-for="item in this.placeArray"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="接种日期:" prop="orderTime">
                        <el-date-picker
                                v-model="form.orderTime"
                                type="date"
                                placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="validatorSub('ruleForm')">提交</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </el-form>

            </el-dialog>

            <el-dialog title="预约信息查询" v-model="vis4" :before-close="handleDialogClose2">
                <el-descriptions v-if="this.showFlag === 1">
                    <el-descriptions-item label="预约状态:">
                        <span v-if="this.orderQueryForm.status === 0" style="color: orange">未审核</span>
                        <span v-if="this.orderQueryForm.status === 1" style="color: green">审核通过</span>
                        <span v-if="this.orderQueryForm.status === 2" style="color: red">未通过审核</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="预约编号:">{{this.orderQueryForm.orderNo}}</el-descriptions-item>
                    <el-descriptions-item label="疫苗名称:">{{this.orderQueryForm.vaccineName}}</el-descriptions-item>
                    <el-descriptions-item label="接种地点:">{{this.orderQueryForm.vaccinePlace}}</el-descriptions-item>
                    <el-descriptions-item label="接种时间:">{{this.orderQueryForm.orderTime}}</el-descriptions-item>
                    <el-descriptions-item label="手机号:">{{this.orderQueryForm.phone}}</el-descriptions-item>
                </el-descriptions>
                <el-empty v-if="this.showFlag === 0" description="暂没有您的预约信息"></el-empty>
            </el-dialog>
        </div>
    </ul>
</template>

<script>


    import request from "../utils/request";
    import E from "wangeditor"

    let editor


    export default {
        name: 'vaccine',
        components: {},
        data() {
            var checkPhone = (rule, value, callback) => {
                if (!this.validatePhoneNum(value) && value !== null && value !== '') {
                    callback(new Error('请输入正确的手机号！'));
                } else {
                    callback();
                }
            };
            return {
                pageInfo: {
                    query: '',
                    pageNum: 1,
                    pageSize: 5,
                },
                total: 0,
                tableData: [],
                dialogVisible: false,
                form: {},
                user: {},
                ids: [],
                orderQueryForm: {},
                detalt: {},
                vis: false,
                vis2: false,
                vis3: false,
                vis4: false,
                vaccineId: '',
                placeArray: [],
                dateFormat: '',
                showFlag: '',
                rules: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    phone: [
                        {required: true, validator: checkPhone, trigger: 'blur'}
                    ],
                    address: [
                        {required: true, message: '请输入住址', trigger: 'blur'}
                    ],
                    risk: [
                        {required: true, message: '请选择', trigger: 'blur'}
                    ],
                    vaccinePlace: [
                        {required: true, message: '请选择接种地点', trigger: 'blur'}
                    ],
                    orderTime: [
                        {required: true, message: '请填写接种日期', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            formatDate (data) {
                var date = new Date(data)
                var Y = date.getFullYear() + '-'
                var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
                var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
                return Y + M + D;
            },
            /**
             * @desc 校验国内手机号是否合法
             * @param {String} phoneNum 手机号
             * @return {Boolean}
             */
            validatePhoneNum(phoneNum) {
                const reg = /^1[0-9]{10}$/
                return reg.test(phoneNum)
            },
            handleDialogClose() {
                this.vis3 = false;
                this.placeArray = [];
                this.form = {};
                this.vaccineId = '';
                this.$refs['ruleForm'].resetFields();
            },
            handleDialogClose2() {
                this.vis4 = false;
                this.orderQueryForm = {};
                this.dateFormat = '';
                this.showFlag = '';
            },
            detalts(row) {
                this.detalt = row
                this.vis = true
            },
            detalts1(row) {
                this.detalt = row
                this.vis2 = true
            },
            cancelDialogVisible() {
                this.dialogVisible = false;
                this.form = {};
            },
            changeVis3(row) {
                this.placeArray = [];
                this.form = {};
                this.getVaccinePlace(row.id)
                this.vaccineId = row.id
                this.form.vaccineName = row.name
                this.detalt = row
                this.vis3 = true;
            },
            async orderQuery() {
                const result = await request.get("/vaccine_order/selectByUserId/" + this.user.id);
                if (result.code === '0') {
                    this.orderQueryForm = result.data;
                    this.showFlag = 1;
                } else {
                    this.showFlag = 0;
                }
                this.vis4 = true;
            },
            async getVaccinePlace(id) {
                var pydata = {'id': id};
                const {data: result} = await request.get("/vaccine/getVaccinePlace", {params: pydata})
                for (var i = 0; i < result.length; i++) {
                    this.placeArray.push({label: result[i], value: result[i]})
                }
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            validatorSub(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.submitOrder();
                    } else {
                        return false;
                    }
                });
            },
            async submitOrder() {
                this.vis3 = false;
                this.form.orderTime=this.formatDate(this.form.orderTime);
                this.form.userId = this.user.id;
                const result = await request.post("/vaccine_order/insert/" + this.vaccineId, this.form)
                if (result.code === '0') {
                    this.$message({
                        type: "success",
                        message: "预约成功，等待审核"
                    })
                    this.load();
                } else {
                    this.$message({
                        type: 'error',
                        message: result.msg
                    })
                }
                this.form = {};
                this.placeArray = [];
                this.vaccineId = '';
            },
            deleteBatch() {
                if (!this.ids.length) {
                    this.$message.warning("请选择数据！")
                    return
                }
                console.log(this.ids)
                request.post("/vaccine/deleteBatch", this.ids).then(res => {
                    if (res.code === '0') {
                        this.$message.success("批量删除成功")
                        this.load()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },
            handleSelectionChange(val) {
                this.ids = val.map(v => v.id)   // [{id,name}, {id,name}] => [id,id]
            },
            filesUpload(result) {
                this.form.image = result.data;
            },
            async load() {
                const {data: result} = await request.get("/vaccine/list", {params: this.pageInfo})
                this.tableData = result.rows
                this.total = result.total
            },
            add() {
                this.dialogVisible = true
                this.form = {}
                this.$nextTick(() => {
                    // 关联弹窗里面的div，new一个 editor对象
                    if (!editor) {
                        editor = new E('#div1')
                        // 配置 server 接口地址
                        editor.config.uploadImgServer = 'http://localhost:9090/files/editor/upload'
                        editor.config.uploadFileName = "file"  // 设置上传参数名称
                        editor.create()
                    }
                    editor.txt.html("")
                })
            },
            async save() {
                this.form.details = editor.txt.html()
                if (this.form.id) {//更新
                    const result = await request.put("/vaccine/update", this.form)
                    this.dialogVisible = false
                    if (result.code === '0') {
                        this.$message({
                            type: "success",
                            message: "更新成功"
                        })
                    } else {
                        this.$message({
                            type: 'error',
                            message: result.msg
                        })
                    }
                    this.load();
                    this.form = {};
                } else {//新增
                    const result = await request.post("/vaccine/insert", this.form)
                    this.dialogVisible = false
                    if (result.code === '0') {
                        this.$message({
                            type: "success",
                            message: "新增成功"
                        })
                        editor.txt.clear()
                    } else {
                        this.$message({
                            type: 'error',
                            message: result.msg
                        })
                    }
                    this.load();
                    this.form = {};
                }
            },
            handleEdit(row) {
                this.form = JSON.parse(JSON.stringify(row))
                this.dialogVisible = true
                this.$nextTick(() => {
                    // 关联弹窗里面的div，new一个 editor对象
                    // 关联弹窗里面的div，new一个 editor对象
                    if (!editor) {
                        editor = new E('#div1')
                        // 配置 server 接口地址
                        editor.config.uploadImgServer = 'http://localhost:9090/files/editor/upload'
                        editor.config.uploadFileName = "file"  // 设置上传参数名称
                        editor.create()
                    }
                    editor.txt.html(row.details)
                })
            },
            handleDelete(id) {
                request.delete("/vaccine/delete?id=" + id).then(result => {
                    if (result.code === '0') {
                        this.$message({
                            type: "success",
                            message: "删除成功！"
                        })
                    } else {
                        this.$message({
                            type: "error",
                            message: result.msg
                        })
                    }
                    this.load()
                    console.log(id)
                })


            },
            handleSizeChange(pageSize) {
                this.pageInfo.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                this.pageInfo.pageNum = pageNum
                this.load()
            },
            fileUploadSuccess(result) {
                console.log(result)
            },
            async checkUser() {
                const result = await request.get("/user/" + this.user.id)
                if (result === '0') {
                    this.user = result.data
                }
            },
            order() {
                this.vis3 = false;
            }
        }
        ,
        created() {
            this.load()
            let userStr = sessionStorage.getItem("user") || "{}"
            this.user = JSON.parse(userStr)
        }
    }
</script>
<style scoped>
    .el_botton{
        color: #fff;
        background-color: #5470c6;
        border-color: #5470c6;
    }
</style>
